#include "searchnode.h"

SearchNode::SearchNode(const PuzzleState& state, int g, int h, 
                       std::shared_ptr<SearchNode> parent, int action)
    : state(state), g(g), h(h), parent(parent), action(action)
{
}

SearchNode::SearchNode(const PuzzleState& state, std::shared_ptr<SearchNode> parent)
    : state(state), g(0), h(0), parent(parent), action(-1)
{
    // 如果有父节点，则g值为父节点的g值+1
    if (parent) {
        g = parent->getG() + 1;
    }
}

SearchNode::SearchNode(const PuzzleState& state, std::shared_ptr<SearchNode> parent, int action, int g)
    : state(state), g(g), h(0), parent(parent), action(action)
{
}

int SearchNode::getDepth() const
{
    if (isRoot()) {
        return 0;
    }
    return parent->getDepth() + 1;
}

std::vector<PuzzleState> SearchNode::getPath() const
{
    std::vector<PuzzleState> path;
    auto node = shared_from_this();
    while (node) {
        path.push_back(node->getState());
        node = node->getParent();
    }
    std::reverse(path.begin(), path.end());
    return path;
}

std::vector<int> SearchNode::getActionPath() const
{
    std::vector<int> actions;
    auto node = shared_from_this();
    while (node && !node->isRoot()) {
        actions.push_back(node->getAction());
        node = node->getParent();
    }
    std::reverse(actions.begin(), actions.end());
    return actions;
}

bool SearchNode::operator<(const SearchNode& other) const
{
    // 对于优先队列，我们希望f值小的节点优先级高
    // 所以f值小的应该被认为"大于"
    return getF() > other.getF();
}

bool SearchNode::operator>(const SearchNode& other) const
{
    return getF() < other.getF();
}

bool SearchNode::operator==(const SearchNode& other) const
{
    return state == other.state;
}